import asyncio, re
import json
from jsonpath import jsonpath
import websockets
import sys
from PyQt5.QtCore import Qt, QSize, pyqtSignal, QThread, QObject, pyqtSlot
from PyQt5.QtGui import QMovie
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel

class WebSocketWorker(QObject):
    like_count_updated = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self.loop = asyncio.new_event_loop()

    @pyqtSlot()
    def start(self):
        asyncio.set_event_loop(self.loop)
        self.loop.run_until_complete(self.websocket_client())

    async def websocket_client(self):
        async with websockets.connect("ws://172.168.10.92:8888/133420146568?use=2", ping_interval=None) as ws:
            await ws.send("token")
            while True:
                result = await ws.recv()
                json_data = json.loads(result)
                self.check_json(json_data)

    def check_json(self, json_data):
        Token = json_data.get("Type")
        if Token == 2:  # 假设 Type 2 是点赞数更新
            try:
                new_like_count = jsonpath(json.loads(json_data.get("Data")), '$.Content')[0]
                match = re.search(r'总点赞(\d+)', new_like_count)

                # 更新点赞数（同时也是功德数）并发射信号
                self.like_count_updated.emit(int(match.group(1)))
            except Exception as e:
                print(f"Error processing JSON: {e}")

class DouyinLikeWoodenFishApp(QWidget):
    def __init__(self):
        super().__init__()

        # 初始化变量
        self.like_count = 0  # 现在这个变量同时表示点赞数和功德数

        # 设置窗口无边框和透明背景
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
        self.setAttribute(Qt.WA_TranslucentBackground)

        # 初始化用户界面
        self.initUI()

        # 启动 WebSocket 工作线程
        self.websocket_worker = WebSocketWorker()
        self.websocket_worker.like_count_updated.connect(self.update_like_label)
        self.websocket_thread = QThread()
        self.websocket_worker.moveToThread(self.websocket_thread)
        self.websocket_thread.started.connect(self.websocket_worker.start)
        self.websocket_thread.start()

    def initUI(self):
        # 布局
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)

        # GIF动图显示
        self.gif_label = QLabel(self)
        movie = QMovie("muyu.gif")  # 替换为你的GIF文件路径
        movie.setScaledSize(QSize(200, 200))  # 根据需要设置GIF的大小
        self.gif_label.setMovie(movie)
        movie.start()
        layout.addWidget(self.gif_label)

        # 点赞数（同时也是功德数）显示
        self.like_label = QLabel(f'点赞/功德数: {self.like_count}', self)
        self.like_label.setStyleSheet("color: white; font-size: 32px; font-family: Arial;")
        layout.addWidget(self.like_label)

        # # 点赞/敲木鱼按钮
        # self.like_button = QPushButton('点赞/敲木鱼', self)
        # self.like_button.clicked.connect(self.on_like_button_clicked)
        # layout.addWidget(self.like_button)

    def update_like_label(self, new_like_count):
        # 更新点赞数（同时也是功德数）标签
        self.like_count = new_like_count
        self.like_label.setText(f'点赞/功德数: {self.like_count}')

    # def on_like_button_clicked(self):
    #     # 增加点赞数（同时也是功德数）
    #     self.like_count += 1
    #     self.like_label.setText(f'点赞/功德数: {self.like_count}')
    #     # 这里可以选择是否通过WebSocket发送消息来更新服务器端的点赞数

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = DouyinLikeWoodenFishApp()
    ex.show()
    sys.exit(app.exec_())